package com.qingxin.ui.bean;

import java.io.File;
import java.util.HashMap;


/**
 * 用于加载UI配置
 */
public class UILoader {
	//缓存已加载的布局配置
	private static final HashMap<String, UILayout> UILAYOUT_MAP;
	
	static{
		UILAYOUT_MAP = new HashMap<String, UILayout>();
	}
	
	/**
	 * 获取指定UI布局配置
	 * @param moduleCode
	 * @param dynamicReplacer
	 * @return
	 */
	public synchronized static UILayout getUILayout(String moduleCode, UIDynamicReplacer dynamicReplacer){
		moduleCode = moduleCode.toLowerCase();
		if(UIParam.DEBUG){//调试模式
			UILayout layout = null;
			try {
				XMLDigester digester = new XMLDigester(UILoader.class.getResource(UIParam.CONFIG_RULE_FILE));
				digester.setSubstitutor(new UITextSubstitutor(dynamicReplacer));
				
				String filename = UIParam.DEBUG_PATH + UIParam.CONFIG_PATH + "/" + moduleCode + UIParam.CONFIG_SUFFIX;
				layout = (UILayout) digester.parse(new File(filename));
			} catch (Exception e) {
				e.printStackTrace();
			}
			return layout;
		}else{//正常模式
			UILayout layout = UILAYOUT_MAP.get(moduleCode);
			if(layout!=null){
				return layout;
			}
			try {
				XMLDigester digester = new XMLDigester(UILoader.class.getResource(UIParam.CONFIG_RULE_FILE));
				digester.setSubstitutor(new UITextSubstitutor(dynamicReplacer));
				
				String path = UIParam.CONFIG_PATH + "/" + moduleCode + UIParam.CONFIG_SUFFIX;
				layout = (UILayout) digester.parse(UILoader.class.getResource(path));
				
				UILAYOUT_MAP.put(moduleCode, layout);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return layout;
		}
	}
	
	
	/**
	 * 清除缓存数据
	 */
	public synchronized static void clear(){
		UILAYOUT_MAP.clear();
	}
	
}
